package cn.ddiancan.xddcloud.common.interceptor;

import java.io.IOException;
import java.util.Objects;

import cn.ddiancan.xddcloud.common.constants.XddHeaderConstant;
import cn.ddiancan.xddcloud.common.context.RequestContext;
import cn.ddiancan.xddcloud.common.entity.UserVO;
import cn.ddiancan.xddcloud.common.security.JwtService;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StringUtils;

public class JWTInterceptor implements ClientHttpRequestInterceptor {

    private final JwtService jwtService;

    public JWTInterceptor(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
        // jwttoken必须持续传递，做用户信息持续下沉
        UserVO userVO = RequestContext.getCurrentContextUser();
        if (Objects.isNull(userVO)) {
            return execution.execute(request, body);
        }
        String jwtServiceToken = jwtService.createToken(userVO);
        if (StringUtils.hasText(jwtServiceToken)) {
            request.getHeaders().add(XddHeaderConstant.X_JWT_TOKEN, jwtServiceToken);
        }
        return execution.execute(request, body);
    }
}
